﻿using PayrollHR.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Payroll.BusinessLogic.Messages;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic;
using System.Data;
using Payroll.Common.Utils;

namespace PayrollHR.Administration.Modules
{
    public partial class MessageControl : BaseAdministrationUserControl
    {
        string gvUniqueID = String.Empty;
        int gvNewPageIndex = 0;
        int gvEditIndex = -1;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.SetDefaul();
            }
        }
        #region Function
        private CustomerSearchResult GetSearchResult()
        {
            return new CustomerSearchResult
            {
                CustName = txtCustName.Text.Trim(),
                PackageName = txtPackName.Text.Trim(),
                packageCode = txtMaCode.Text.Trim(),
                CustEmail = txtCustEmail.Text.Trim(),
                CustMobile = txtMobile.Text.Trim(),
                TaxCode = txtTaxcode.Text.Trim(),
                From = dpFromdate.SelectText,
                To = dpTodate.SelectText,
                Confirm = ckConfirm.Checked ? 2 : 3,
                Distributor = txtCustomerName.Text.Trim(),
                UserId = PayrollContext.Current.Session.EmployeeId
            };
        }
        protected void BindGrid(ref List<MessageMails> List)
        {
            var resultSearch = GetSearchResult();
            List = this.MessageService.GetMessge(packageCode: resultSearch.packageCode, fromdate: resultSearch.From, todate: resultSearch.To, Distributor: resultSearch.Distributor,
                customerName: resultSearch.CustName, taxcode: resultSearch.TaxCode, mobile: resultSearch.CustMobile, email: resultSearch.CustEmail, confrim: resultSearch.Confirm);
        }
        protected void Bind(List<MessageMails> List)
        {
            gvMessage.DataSource = List;
            gvMessage.DataBind();
        }
        protected void Bind()
        {
            List<MessageMails> List = new List<MessageMails>();
            this.BindGrid(ref List);
            this.Bind(List);
        }
        protected void SetDefaul()
        {
            dpFromdate.SelectText = DateTime.Now.ToString("dd/MM/yyyy");
            dpTodate.SelectText = DateTime.Now.ToString("dd/MM/yyyy");
        }
        protected void Delete()
        {
            if (Page.IsValid)
            {
                int Row = gvMessage.Rows.Count;
                string result = "";
                try
                {
                    foreach (GridViewRow row in gvMessage.Rows)
                    {
                        var cbMessage = row.FindControl("cbMessage") as CheckBox;
                        var hfhfMessageID = row.FindControl("hfMessageID") as HiddenField;
                        bool isChecked = cbMessage.Checked;
                        if (isChecked)
                        {
                            result += hfhfMessageID.Value + ",";
                        }
                    }
                    if (result.Length > 0)
                    {
                        result = result.Substring(0, result.Length - 1);
                        var resultSearch = GetSearchResult();
                        List<MessageMails> List = this.MessageService.Delete(MessageId: result, packageCode: resultSearch.packageCode, fromdate: resultSearch.From, todate: resultSearch.To, Distributor: resultSearch.Distributor,
                            customerName: resultSearch.CustName, taxcode: resultSearch.TaxCode, mobile: resultSearch.CustMobile, email: resultSearch.CustEmail);
                        this.Bind(List);
                    }
                }
                catch (Exception ex)
                {
                    ProcessException(ex);
                }
            }
        }
        protected void SendQueued()
        {
            string MessageID = "";
            try
            {
                foreach (GridViewRow row in gvMessage.Rows)
                {
                    var cbMessage = row.FindControl("cbMessage") as CheckBox;
                    var hfMessageID = row.FindControl("hfMessageID") as HiddenField;
                    bool isChecked = cbMessage.Checked;
                    if (isChecked)
                    {
                        MessageID += hfMessageID.Value + ",";
                    }
                }
                if (MessageID.Length > 0)
                {
                    MessageID = MessageID.Substring(0, MessageID.Length - 1);
                    this.MessageService.SaveQueuedEmail(MessageID, HttpContext.Current.Request.PhysicalApplicationPath);
                }
                this.Bind();
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
        }
        #endregion
        #region event button
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            this.Bind();
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            this.SendQueued();
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            this.Delete();
        }
        #endregion
        #region grid event
        protected void gvMessage_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvMessage.PageIndex = e.NewPageIndex;
            this.Bind();
        }
        protected void gvMessage_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow row = e.Row;
            if (row.DataItem == null)
            {
                return;
            }

            int confirm = ckConfirm.Checked ? 2 : 3;
            GridView gv = new GridView();
            gv = (GridView)row.FindControl("gvMail");
            object obj = gvMessage.DataKeys[row.RowIndex].Value;
            if (gv.UniqueID == gvUniqueID)
            {
                gv.PageIndex = gvNewPageIndex;
                gv.EditIndex = gvEditIndex;
                //Expand the Child grid
                Page.ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + obj.ToString() + "','one');</script>");
                //ScriptManager.RegisterStartupScript(upEmailReceive, upEmailReceive.GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + obj.ToString() + "','one');</script>", true);
            }
            int MessgeID = CommonHelper.ToInteger(obj);
            gv.DataSource = this.ResultService.GetbyMessageID(MessgeID, confirm);
            gv.DataBind();
        }
        protected void gvMail_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gvTemp = (GridView)sender;
                gvUniqueID = gvTemp.UniqueID;

                GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];

                TextBox txtCustomerName = (TextBox)row.FindControl("txtCustomerName");
                TextBox txtTaxCode = (TextBox)row.FindControl("txtTaxCode");
                TextBox txtMobile = (TextBox)row.FindControl("txtMobile");
                TextBox txtDatePurchase = (TextBox)row.FindControl("txtDatePurchase");
                TextBox txtPackageCode = (TextBox)row.FindControl("txtPackageCode");
                TextBox txtCustomerProfile = (TextBox)row.FindControl("txtCustomerProfile");
                HiddenField hfMessageID = (HiddenField)row.FindControl("hfMessageID");
                HiddenField hfResultsId = (HiddenField)row.FindControl("hfResultsId");
                this.ResultService.Save(new Results
                {
                    ResultsId = CommonHelper.ToInteger(hfResultsId.Value),
                    PackageCode = txtPackageCode.Text.Trim(),
                    DatePurchase = txtDatePurchase.Text.Trim(),
                    TaxCode = txtTaxCode.Text.Trim(),
                    Mobile = txtMobile.Text.Trim(),
                    CustomerName = txtCustomerName.Text.Trim(),
                    CustomerProfile = txtCustomerProfile.Text.Trim(),
                    MessageID = CommonHelper.ToInteger(hfMessageID.Value)
                });
                gvEditIndex = -1;
                this.Bind();
            }
            catch { }
        }

        protected void gvMail_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            gvEditIndex = e.NewEditIndex;
            this.Bind();
        }

        protected void gvMail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            gvEditIndex = -1;
            this.Bind();
        }
        protected void gvMail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            gvNewPageIndex = e.NewPageIndex;
            this.Bind();
        }
        protected void gvMail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("AddDetail"))
            {
                try
                {
                    GridView gvTemp = (GridView)sender;
                    gvUniqueID = gvTemp.UniqueID;
                    TextBox txtCustomerName = (TextBox)gvTemp.FooterRow.FindControl("txtCustomerName");
                    TextBox txtTaxCode = (TextBox)gvTemp.FooterRow.FindControl("txtTaxCode");
                    TextBox txtMobile = (TextBox)gvTemp.FooterRow.FindControl("txtMobile");
                    TextBox txtDatePurchase = (TextBox)gvTemp.FooterRow.FindControl("txtDatePurchase");
                    TextBox txtPackageCode = (TextBox)gvTemp.FooterRow.FindControl("txtPackageCode");
                    TextBox txtAddress = (TextBox)gvTemp.FooterRow.FindControl("txtAddress");
                    TextBox txtCustomerProfile = (TextBox)gvTemp.FooterRow.FindControl("txtCustomerProfile");
                    string MessageId = gvTemp.DataKeys[0].Value.ToString();
                    this.ResultService.Save(new Results
                    {
                        PackageCode = txtPackageCode.Text.Trim(),
                        DatePurchase = txtDatePurchase.Text.Trim(),
                        TaxCode = txtTaxCode.Text.Trim(),
                        Mobile = txtMobile.Text.Trim(),
                        CustomerName = txtCustomerName.Text.Trim(),
                        CustomerProfile = txtCustomerProfile.Text.Trim(),
                        MessageID = CommonHelper.ToInteger(MessageId)
                    });
                    this.Bind();
                    Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Thêm gói cước thành công');</script>");
                }
                catch (Exception ex)
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Thêm gói cước không thành công');</script>");
                }
            }
        }
        protected void gvMail_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            try
            {
                GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
                HiddenField hfResultsId = (HiddenField)row.FindControl("hfResultsId"); 
                this.ResultService.Delete(CommonHelper.ToInteger(hfResultsId.Value));
                this.Bind();
                Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Xóa khách hàng thành công');</script>");
            }
            catch { }
        }

        protected void gvMail_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            //Check if there is any exception while deleting
            if (e.Exception != null)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
                e.ExceptionHandled = true;
            }
        }
        #endregion
    }
}